import 'package:flutter/foundation.dart';

/// Data Access Layer (DAL) context.
abstract class DalContext extends ChangeNotifier {
  bool _isInitialized = false;
  bool get isInitialized => _isInitialized;
  bool _isDisposed = false;
  bool get isDisposed => _isDisposed;

  /// Initializes the DAL context.
  Future<bool> init() async {
    if (_isInitialized) return true;
    return await onInit();
  }

  /// Resets the DAL context.
  /// @param [cascade] If true, it will reset all child contexts as well.
  Future<bool> reset([bool cascade = true]) async {
    return await onReset();
  }

  /// Dispose the DAL context.
  /// This method should be called when the DAL context is no longer needed.
  /// It is important to clean up resources to prevent memory leaks.
  @override
  void dispose() {
    if (isDisposed) return;
    onDisposed();
    super.dispose();
  }

  @override
  bool operator ==(Object other) {
    return identical(this, other);
  }

  @override
  int get hashCode => identityHashCode(this);

  /// Creates the DAL context.
  /// This method should be called when the DAL context is created.
  @protected
  void onCreate() {}

  /// Initializes resources after the DAL context is created.
  @protected
  Future<bool> onInit() async {
    _isInitialized = true;
    return true;
  }

  /// Cleans up resources when the DAL context is reseted.
  @protected
  Future<bool> onReset() async {
    _isInitialized = false;
    return true;
  }

  /// Cleans up resources when the DAL context is destroied.
  @protected
  void onDisposed() {
    _isDisposed = true;
  }
}
